package com.scm.java.net.sup.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.map.HashedMap;

import com.scm.entity.base.DrugSns;
import com.scm.entity.base.SupDrugIn;
import com.scm.entity.base.SupDrugStock;
import com.scm.java.net.dao.CommonDao;
import com.scm.java.net.utils.StringUtils;

public class DrugInServiceImpl implements DrugInService{

	@Override
	public void add(SupDrugIn drugIn, List<DrugSns> snList,
			List<SupDrugStock> drugStockList, CommonDao dao) throws Exception {
		dao.addObj("drugin.addDrug", drugIn);
		dao.batchInsert("drugStock.addStock", drugStockList);
		dao.batchInsert("drugStock.addSns", snList);
	}
     /**
      * 编辑入库单
     * @throws Exception 
      */
	@Override
	public void edit(SupDrugIn drugIn,String[] sns, CommonDao dao) throws Exception {
		// TODO Auto-generated method stub
		if(sns!=null&& sns.length > 0){
			List<DrugSns> snList = new ArrayList<DrugSns>();
			List<SupDrugStock> drugStockList = new ArrayList<SupDrugStock>();
			for (int i = 0; i < sns.length; i++) {
				// 串号表
				String[] sn = sns[i].split(",");
				DrugSns dsns = new DrugSns();
				dsns.setId(StringUtils.uniqueKey());
				dsns.setInvoiceid(drugIn.getInvoiceid());
				dsns.setSn1(sn[0]);
				dsns.setSn2(sn[1]);
				snList.add(dsns);
				// 库存表
				SupDrugStock drugStock = new SupDrugStock();
				drugStock.setSn1(sn[0]);
				drugStock.setSn2(sn[1]);
				drugStock.setStatus(0);
				BeanUtils.copyProperties(drugStock, drugIn);
				drugStockList.add(drugStock);
			}
			dao.batchInsert("drugStock.addStock", drugStockList);
			dao.batchInsert("drugStock.addSns", snList);
		}
		//更新入库单
		dao.editObj("drugin.editDrug", drugIn);
		Map paraMap=new HashedMap();
		paraMap.put("drugIn", drugIn);
		//取出供应商号为drugIn的序号
		List<DrugSns> snsList=dao.queryList("drugStock.getSns", paraMap);
		if(snsList!=null&&snsList.size()>0){
			for(DrugSns dsns:snsList){
				SupDrugStock stock=new SupDrugStock();
				stock.setSn1(dsns.getSn1());
				stock.setSn2(dsns.getSn2());
				BeanUtils.copyProperties(stock, drugIn);
				dao.editObj("drugStock.editStock", stock);
			}
		}
	    
	}
	@Override
	public void del(SupDrugIn drugIn,CommonDao dao) throws Exception{
		// TODO Auto-generated method stub
		Map paraMap=new HashedMap();
		paraMap.put("drugIn", drugIn);
		//取出供应商号为drugIn的序号
		List<DrugSns> snsList=dao.queryList("drugStock.getSns", paraMap);
		if(snsList!=null&&snsList.size()>0){
			for(DrugSns sns:snsList){
				//删除入库单
				SupDrugStock stock=new SupDrugStock();
				stock.setSn1(sns.getSn1());
				dao.del("drugStock.deleteStock", stock);
				//删除序号
				dao.del("drugStock.deleteSns", sns);
			}
		}
		//删除库层单
		dao.del("drugin.deleteDrugIn", drugIn);
	}


}
